package User

import (
	"MyWork_/Dbutil"
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

type Message struct {
	Sender   string
	Receiver string
	Content  string
}

func User(name string) {
	conn := connectToSever(name)
	for true {
		//与客户端进行连接

		//菜单
		fmt.Printf("----------%v----------\n", name)
		fmt.Println("       1.广播发送消息")
		fmt.Println("       2.私信")
		fmt.Println("       3.退出账号")
		fmt.Printf("请输入（按回车键确定）：")
		selecter := 0
		fmt.Scanln(&selecter)
		if selecter == 1 {
			Input(conn, name, "1")
		} else if selecter == 2 {
			fmt.Printf("请输入对方用户名：")
			receiver := reader()
			//用户输入
			if receiver == "" || receiver == " " || receiver == "\n" {
				fmt.Println("用户名不合法")
				continue
			} else {
				Input(conn, name, receiver)

			}

		} else if selecter == 3 {
			quit(conn, name, "")
			return
		} else {
			fmt.Printf("输入选项不正确，请重新输入┗( ▔, ▔ )┛，按回车键继续...")
			fmt.Scanln()
		}

	}
}

//读取用户的输入
func reader() string {
	inputReader := bufio.NewReader(os.Stdin)
	input, _ := inputReader.ReadString('\n') // 读取用户输入
	inputInfo := strings.Trim(input, "\r\n")
	return inputInfo
}

//输入消息

func Input(conn net.Conn, name string, recer string) {

	inputReader := bufio.NewReader(os.Stdin)
	go receiveAll(conn)

	for {
		input, _ := inputReader.ReadString('\n') // 读取用户输入
		inputInfo := strings.Trim(input, "\r\n")
		if strings.ToUpper(inputInfo) == "Q" { // 如果输入q就退出
			break
		}

		sendMessage(name, recer, inputInfo, conn)

	}

}

//发送消息，可以私发，可以广播发送
func sendMessage(name string, recer string, content string, conn net.Conn) {
	//写入信息
	message := Message{name, recer, content}
	//JSON序列化：结构体-->JSON格式的字符串
	data, err := json.Marshal(message)
	if err != nil {
		fmt.Println("json marshal failed")
		return
	}

	_, err = conn.Write(data)
	//fmt.Println(name, recer, content)
	if err != nil {
		fmt.Println("Send err:", err)
	}
}

//最后退出登陆的时候关闭连接
func quit(conn net.Conn, name string, recer string) {
	//修改数据库该用户的状态信息
	Dbutil.UserQuit(name)
	//给服务器端发送下线通知
	sendMessage(name, "drop", "drop", conn)
	time.Sleep(time.Second)
	conn.Close()
}

func receiveAll(conn net.Conn) {
	for {
		var buf [128]byte
		n, err := conn.Read(buf[:])
		if err != nil {
			fmt.Println("退出成功")
			return
		}
		fmt.Println(string(buf[:n]))
	}
}

//与服务器建立连接接 把用户名发给服务器
func connectToSever(name string) net.Conn {
	conn, err := net.Dial("tcp", "127.0.0.1:20000")
	if err != nil {
		fmt.Println("err :", err)
		return nil
	}
	_, err = conn.Write([]byte(name)) //发送用户名
	if err != nil {
		fmt.Println("err:", err)
	}
	return conn
}
